package com.example.rdcproject.ving.notes.view.User;

import com.example.rdcproject.ving.notes.entity.User;
import com.example.rdcproject.ving.notes.util.UserSearchUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class RankView extends JFrame {

    private List<User> userList = new ArrayList<User>();

    public RankView()  {
        JFrame frameRank = new JFrame("排行榜");
        frameRank.setLayout(new BorderLayout());

        frameRank.setSize(500,500);

        JPanel panelRank = new JPanel(new GridLayout(3, 3));

        UserSearchUtil searchUtil = new UserSearchUtil();
         userList = searchUtil.searchRank();

         //按照背单词多少排序，如果一样按照打卡天数排序
        Collections.sort(userList, new Comparator<User>() {
            @Override
            public int compare(User u1, User u2) {
                // 根据背单词总数或者连续打卡天数进行排序
                int diff = u2.getWordCount() - u1.getWordCount();
                 if (diff==0){
                     int diff2 =u2.getContinuousDays()-u1.getContinuousDays();
                     return  diff2;
                 }else {

                     return diff;
                 }
            }
        });

        // 将排行榜数据展示在JTable中
        String[] column = {"排行榜", "昵称", "学习的单词总数", "连续学习打卡天数"};
        Object[][] row = new Object[userList.size()][4];
        for (int i = 0; i < 3; i++) {
            row[i][0] = i + 1; // 排名
            row[i][1] = userList.get(i).getNickname();
            row[i][2] = userList.get(i).getWordCount();
            row[i][3] = userList.get(i).getContinuousDays();
        }

        DefaultTableModel model = new DefaultTableModel(row, column);
        JTable table = new JTable(model);
        JScrollPane scrollPane = new JScrollPane(table);


        panelRank.add(scrollPane);

        //添加容器
        frameRank.add(panelRank);

        //获取数据
        frameRank.setVisible(true);
        frameRank.pack();

        frameRank.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

}
